﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Data.Performance
{
    /// <summary>
    /// list于Dictionary关联查询
    /// </summary>
    public class ListToDictionary
    {
        public static ListToDictionary CreateStatic()
        {
            return new ListToDictionary();
        }

        public ListToDictionary()
        {
            userInfos = new List<UserInfo>();
            userInfoDic = new Dictionary<int, UserInfo>();
            for (int i = 0; i < 10000; i++)
            {
                userInfos.Add(new UserInfo { Id = i, Name = $"{i}的名称" });
            }
            userInfoDic = userInfos.ToDictionary(x => x.Id, x => x);
        }


        public List<UserInfo> userInfos;

        public Dictionary<int, UserInfo> userInfoDic;


        public void ListToDictionaryPerformanceTest()
        {
            System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
            sw.Start();
            for (int i = 0; i < 1000; i++)
            {
                var user = userInfos.Where(x => x.Id == i).FirstOrDefault();
            }
            sw.Stop();
            TimeSpan ts = sw.Elapsed;
            Console.WriteLine($"list运行time： {ts.TotalMilliseconds}");


            System.Diagnostics.Stopwatch sw2 = new System.Diagnostics.Stopwatch();
            sw2.Start();
            for (int i = 0; i < 1000; i++)
            {
                var user = userInfoDic[i];
            }
            sw2.Stop();
            TimeSpan ts2 = sw2.Elapsed;
            Console.WriteLine($"Dictionary运行time： {ts2.TotalMilliseconds}");
        }

        public class UserInfo
        {
            public int Id { get; set; }


            public string Name { get; set; }
        }

    }



}
